import { generateCode } from '../core/blockly-init';
import * as Blockly from 'blockly';
// 代码面板类
export class CodePanel {
  constructor(private codeDiv: HTMLElement, private outputDiv: HTMLElement, private workspace: Blockly.Workspace) {
    this.codeDiv = codeDiv;
    this.outputDiv = outputDiv;
    this.workspace = workspace;
     this.createExecuteButton();
  }

  // 创建执行按钮
  createExecuteButton() {
    const button = document.getElementById('executeButton');
    // button.textContent = '执行代码';
    // button.style.marginTop = '10px';
    // button.style.padding = '5px 10px';
    button.addEventListener('click', () => this.executeCode());

    // this.codeDiv.parentNode.appendChild(button);
    return button;
  }

  // 更新代码显示
  updateCode() {
    const code = generateCode(this.workspace);
    this.codeDiv.textContent = code;
  }

  // 执行代码
  executeCode() {
    // 清空输出区域
    this.outputDiv.innerHTML = '';

    // 获取当前显示的代码
    const codeToExecute = this.codeDiv.textContent;

    // 将代码包装在异步 main 函数中
    const wrappedCode = `
async function main() {
  try {
    ${codeToExecute}
  } catch (error) {
    console.error('执行代码时出错:', error);
    document.getElementById('output').innerHTML += '<div style="color: red;">错误: ' + error.message + '</div>';
  }
}

// 立即执行 main 函数
main().catch(error => {
  console.error('执行 main 函数时出错:', error);
  document.getElementById('output').innerHTML += '<div style="color: red;">错误: ' + error.message + '</div>';
});
`;

    console.log('执行代码:', wrappedCode);

    // 执行包装后的代码
    try {
      eval(wrappedCode);
    } catch (error) {
      console.error('评估代码时出错:', error);
      this.outputDiv.innerHTML +=
        '<div style="color: red;">错误: ' + error.message + '</div>';
    }
  }
}
